// 本地存储工具类
const config = require('../config/config.js')

class Storage {
  constructor() {
    this.cacheKeys = config.cacheKeys
    this.cacheExpire = config.cacheExpire
  }

  // 设置缓存（带过期时间）
  set(key, value, expire) {
    try {
      const data = {
        value: value,
        timestamp: Date.now(),
        expire: expire || this.cacheExpire[key] || 0
      }
      wx.setStorageSync(key, JSON.stringify(data))
      return true
    } catch (error) {
      console.error('Storage set error:', error)
      return false
    }
  }

  // 获取缓存
  get(key) {
    try {
      const dataStr = wx.getStorageSync(key)
      if (!dataStr) return null

      const data = JSON.parse(dataStr)
      
      // 检查是否过期
      if (data.expire > 0 && Date.now() - data.timestamp > data.expire) {
        this.remove(key)
        return null
      }

      return data.value
    } catch (error) {
      console.error('Storage get error:', error)
      return null
    }
  }

  // 删除缓存
  remove(key) {
    try {
      wx.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('Storage remove error:', error)
      return false
    }
  }

  // 清空所有缓存
  clear() {
    try {
      wx.clearStorageSync()
      return true
    } catch (error) {
      console.error('Storage clear error:', error)
      return false
    }
  }

  // Token相关操作
  setToken(token) {
    return this.set(this.cacheKeys.token, token)
  }

  getToken() {
    return this.get(this.cacheKeys.token)
  }

  removeToken() {
    return this.remove(this.cacheKeys.token)
  }

  // 用户信息相关操作
  setUserInfo(userInfo) {
    return this.set(this.cacheKeys.userInfo, userInfo)
  }

  getUserInfo() {
    return this.get(this.cacheKeys.userInfo)
  }

  removeUserInfo() {
    return this.remove(this.cacheKeys.userInfo)
  }

  // 购物车相关操作
  setCartItems(items) {
    return this.set(this.cacheKeys.cartItems, items)
  }

  getCartItems() {
    return this.get(this.cacheKeys.cartItems) || []
  }

  removeCartItems() {
    return this.remove(this.cacheKeys.cartItems)
  }

  // 搜索历史相关操作
  setSearchHistory(history) {
    return this.set(this.cacheKeys.searchHistory, history)
  }

  getSearchHistory() {
    return this.get(this.cacheKeys.searchHistory) || []
  }

  addSearchHistory(keyword) {
    if (!keyword || keyword.trim() === '') return

    let history = this.getSearchHistory()
    
    // 移除重复项
    history = history.filter(item => item !== keyword)
    
    // 添加到开头
    history.unshift(keyword)
    
    // 限制数量
    if (history.length > 10) {
      history = history.slice(0, 10)
    }
    
    this.setSearchHistory(history)
  }

  removeSearchHistory() {
    return this.remove(this.cacheKeys.searchHistory)
  }

  // 获取缓存信息
  getCacheInfo() {
    try {
      const info = wx.getStorageInfoSync()
      return {
        keys: info.keys,
        currentSize: info.currentSize,
        limitSize: info.limitSize
      }
    } catch (error) {
      console.error('Get cache info error:', error)
      return null
    }
  }

  // 检查缓存是否存在
  has(key) {
    return this.get(key) !== null
  }

  // 批量设置
  setBatch(data) {
    const results = {}
    for (const key in data) {
      results[key] = this.set(key, data[key])
    }
    return results
  }

  // 批量获取
  getBatch(keys) {
    const results = {}
    keys.forEach(key => {
      results[key] = this.get(key)
    })
    return results
  }

  // 批量删除
  removeBatch(keys) {
    const results = {}
    keys.forEach(key => {
      results[key] = this.remove(key)
    })
    return results
  }
}

// 创建存储实例
const storage = new Storage()

module.exports = storage